var facenames = [ "[微笑]", "[撇嘴]", "[色]", "[发呆]", "[得意]", "[流泪]", "[害羞]",
		"[闭嘴]", "[睡]", "[大哭]", "[尴尬]", "[发怒]", "[调皮]", "[呲牙]", "[惊讶]", "[难过]",
		"[酷]", "[冷汗]", "[抓狂]", "[吐]", "[偷笑]", "[愉快]", "[白眼]", "[傲慢]", "[饥饿]",
		"[困]", "[惊恐]", "[流汗]", "[憨笑]", "[悠闲]", "[奋斗]", "[咒骂]", "[疑问]", "[嘘]",
		"[晕]", "[疯了]", "[衰]", "[骷髅]", "[敲打]", "[再见]", "[擦汗]", "[抠鼻]", "[鼓掌]",
		"[糗大了]", "[坏笑]", "[左哼哼]", "[右哼哼]", "[哈欠]", "[鄙视]", "[委屈]", "[快哭了]",
		"[阴险]", "[亲亲]", "[吓]", "[可怜]", "[菜刀]", "[西瓜]", "[啤酒]", "[篮球]", "[乒乓]",
		"[咖啡]", "[饭]", "[猪头]", "[玫瑰]", "[凋谢]", "[嘴唇]", "[爱心]", "[心碎]", "[蛋糕]",
		"[闪电]", "[炸弹]", "[刀]", "[足球]", "[瓢虫]", "[便便]", "[月亮]", "[太阳]", "[礼物]",
		"[拥抱]", "[强]", "[弱]", "[握手]", "[胜利]", "[抱拳]", "[勾引]", "[拳头]", "[差劲]",
		"[爱你]", "[NO]", "[OK]", "[爱情]", "[飞吻]", "[跳跳]", "[发抖]", "[怄火]", "[转圈]",
		"[磕头]", "[回头]", "[跳绳]", "[挥手]", "[激动]", "[街舞]", "[献吻]", "[左太极]",
		"[右太极]" ];
var faceimgs = [ "0.png", "1.png", "2.png", "3.png", "4.png", "5.png", "6.png",
		"7.png", "8.png", "9.png", "10.png", "12.png", "13.png", "14.png",
		"15.png", "16.png", "17.png", "18.png", "19.png", "20.png", "21.png",
		"22.png", "23.png", "24.png", "25.png", "26.png", "27.png", "28.png",
		"29.png", "30.png", "31.png", "32.png", "33.png", "34.png", "35.png",
		"36.png", "37.png", "38.png", "39.png", "40.png", "41.png", "42.png",
		"43.png", "44.png", "45.png", "46.png", "47.png", "48.png", "49.png",
		"50.png", "51.png", "52.png", "53.png", "54.png", "55.png", "56.png",
		"57.png", "58.png", "59.png", "60.png", "61.png", "62.png", "63.png",
		"64.png", "65.png", "66.png", "67.png", "68.png", "69.png", "70.png",
		"71.png", "72.png", "73.png", "74.png", "75.png", "76.png", "77.png",
		"78.png", "79.png", "80.png", "81.png", "82.png", "83.png", "84.png",
		"85.png", "86.png", "87.png", "88.png", "89.png", "90.png", "91.png",
		"92.png", "93.png", "94.png", "95.png", "96.png", "97.png", "98.png",
		"99.png", "100.png", "101.png", "102.png", "103.png", "104.png",
		"105.png", "106.png", "107.png" ];

var emojis = [ "/::)", "/::~", "/::B", "/::|", "/:8-)", "/::<", "/::$", "/::X",
		"/::Z", "/::'(", "/::-|", "/::@", "/::P", "/::D", "/::O", "/::(",
		"/::+", "/:--b", "/::Q", "/::T", "/:,@P", "/:,@-D", "/::d", "/:,@o",
		"/::g", "/:|-)", "/::!", "/::L", "/::>", "/::,@", "/:,@f", "/::-S",
		"/:?", "/:,@x", "/:,@@", "/::8", "/:,@!", "/:!!!", "/:xx", "/:bye",
		"/:wipe", "/:dig", "/:handclap", "/:&-(", "/:B-)", "/:<@", "/:@>",
		"/::-O", "/:>-|", "/:P-(", "/::'|", "/:X-)", "/::*", "/:@x", "/:8*",
		"/:pd", "/:xxx1", "/:beer", "/:basketb", "/:oo", "/:coffee", "/:eat",
		"/:pig", "/:rose", "/:fade", "/:showlove", "/:heart", "/:break",
		"/:cake", "/:li", "/:bome", "/:kn", "/:footb", "/:ladybug", "/:shit",
		"/:moon", "/:sun", "/:gift", "/:hug", "/:strong", "/:weak", "/:share",
		"/:v", "/:@)", "/:jj", "/:@@", "/:bad", "/:lvu", "/:no", "/:ok",
		"/:love", "/:xxx2", "/:jump", "/:shake", "/:xxx3", "/:circle", "/:kotow",
		"/:turn", "/:skip", "[挥手]", "/:#-0", "[街舞]", "/:kiss", "/:<&", "/:&>"];

/**
 * 对Date的扩展，将 Date 转化为指定格式的String 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 * 可以用 1-2 个占位符 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) eg: (new
 * Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 (new
 * Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04 (new
 * Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04 (new
 * Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 (new
 * Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function(fmt) {
	var o = {
		"M+" : this.getMonth() + 1, // 月份
		"d+" : this.getDate(), // 日
		"h+" : this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小时
		"H+" : this.getHours(), // 小时
		"m+" : this.getMinutes(), // 分
		"s+" : this.getSeconds(), // 秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
		"S" : this.getMilliseconds()
	// 毫秒
	};
	var week = {
		"0" : "/u65e5",
		"1" : "/u4e00",
		"2" : "/u4e8c",
		"3" : "/u4e09",
		"4" : "/u56db",
		"5" : "/u4e94",
		"6" : "/u516d"
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt
				.replace(
						RegExp.$1,
						((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f"
								: "/u5468")
								: "")
								+ week[this.getDay() + ""]);
	}
	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
					: (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
};
var dialogs = [];
var $groups=[];
var $contacts=[];
$(function() {
	$('.window').draggable({
		handle : "header",
		containment : "body"
	});
	setInterval(checkNewMsg, 5000);
	
	// $("body").niceScroll();
	
	var html="";
	for(var i=0;i<data.length;i++){
	
	html+='<li class="list-group-item item" style="padding-bottom: 0px" >';
	html+='	<i class="icon-chevron-right"></i> <span gid="'+data[i].id+'">'+data[i].name+'</span>';
	html+='	<ul class="list-group list-normal m-t-n-xmini scroll-y scrollbar contact_group" id="group'+data[i].id+'"';
	html+='		style="background: #fff;border-radius:0px;">';
	
		for(var j=0;j<data[i].contacts.length;j++){
			var con=data[i].contacts[j];
			html+='			<li style="border: none;" class="list-group-item contact_item" wxid="'+con.wxid+'" onclick="'+"dialog('"+con.wxid+"')"+'">';
			html+='			<img src="'+con.headimgurl+'" alt="">';
			html+='			<small class="pull-right bg-danger  badge m-r">0</small>';
			html+='			<strong>'+con.nickname+'</strong><br>';
			html+='			<small class="city">'+con.province+'&nbsp;'+con.city+'</small>';
			html+='			<i class="icon-chevron-right"></i></li>';
		}
	html+='	</ul>';
	html+='</li>';
	}
	$('#groups').html(html);
	$groups=$('#groups>li');
	$('.contact_item').each(function(){
		$contacts[$contacts.length]=$(this);
	});
	$groups.each(function(){
		$(this).find(">span").click(function(){
			var gid=$(this).attr("gid");
			var $subMenu=$($('#group'+gid));
			$subMenu.css('display');
			$subMenu.css('display',$subMenu.css('display')=='block'?'none':'block');
			// $("#contact_panel_body").niceScroll();
		});
	});
	checkNewMsg();
});
function openChat(){
	var total=$('#newMsgCount').text();
	if(total==0){
		return;
	}
	var $lis=$('li[newMsg="true"]');
	if($lis.size()>0){
		var $li=$($lis.get(0));
		var count=$li.find('.badge').text();
		total=total-count;
		if(total==0){
			$('#newMsgCount').hide();	
		}
		$('#newMsgCount').text(total);	
		$li.click();
	}
	
}
var checking = false;
var newContacts;
function checkNewMsg() {
	if (checking) {
		return;
	}

	var params = "ts="+new Date().getTime()+"&";
	for ( var i = 0; i < dialogs.length; i++) {
		var dialog = dialogs[i].dialog;
		var items = dialog.find('.comment-item');

		params += "wxid=" + dialogs[i].wxid + "&";
		if (items.size() > 0) {
			params += "lastId=" + items.last().attr('mid') + "&";
		} else {
			params += "lastId=0&";
		}
	}
	$.ajax({
		url : "../sms/checkNewMessage.json?" + params,
		dataType : "json",
		beforeSend : function() {
			checking = true;
		},
		success : function(data) {
			checking = false;
			var hasNewContact=data.hasNewContact;
			if(hasNewContact){
				newContacts=data.newContacts;
				
				$('#synBtn .badge').text(newContacts.length);
				$('#synBtn').attr("title","您有新的关注者，点击进行同步数据");
			
				$('#synBtn .badge').show();
				$('#synBtn img').hide();
				$('#synBtn i').show();
				$('#synBtn').show();
				
			}
			var userMsg = data.data;// 获取用户的消息
			if (userMsg) {// 如果有新消息
				for ( var i = 0; i < dialogs.length; i++) {// 在当前已打开的窗口中遍历
					var $dialog = dialogs[i];
					var wxid = $dialog.wxid;// 得到当前打开窗口的用户ID
					var messages = userMsg[wxid];// 得到该用户的消息
					if (messages.length > 0) {// 如果该用户的新消息数量大于0
						for ( var j = 0; j < messages.length; j++) {
							var $li = $('li[wxid="' + wxid + '"]').first();
							var userIcon = $li.find("img").attr('src');
							var message = messages[i];
							message.icon = userIcon;
							$dialog.appendMessage(message);
							
						}
						var $items = $dialog.dialog.find('.comment-list .items').first();
						var $commentlist = $dialog.dialog.find('.comment-list');
						$commentlist.animate({scrollTop : $items.height()}, "slow");
					}

				}
			}

			var result = data.result;
			var count=data.count;
			if (count > 0) {//如果收到新消息
				$('#newMsgCount').text(count).show();
				for(var i=0;i<result.length;i++){
					var $item=getContactItem(result[i].wxid);
					if($item){//如果通讯录里已经有该用户，则在该条目上显示新消息数量
						$item.attr('newMsg',true);
						var badge=$item.find(".badge").first();
						
						badge.text(result[i].count).show();
					}else{
						var $li = $('li[wxid="' + result[i].wxid + '"]').first();
						$li.attr('newMsg',true);
						$li.find('.badge').text(result[i].count).show();
					}
				}
				//sortContacts();
			}
			
			return;
			$('.contact_group li').each(function() {
				$(this).attr('count', 0).find('.badge').hide();
			});
			for ( var i = 0; i < result.length; i++) {
				var item = result[i];
				var $li = $('li[wxid="' + item.wxid + '"]').first();
				$li.attr('count', item.count);
				if (item.count > 0) {
					$li.find('.badge').text(item.count).show();
				} else {
					$li.find('.badge').text(0).hide();

				}
			}
			

		},
		error : function() {

		}
	});
}
function getContactItem(wxid){
	for(var i=0;i<$contacts.length;i++){
		var $item=$($contacts[i]);
		if($item.attr('wxid')==wxid){
			return $item;
		}
	}
	return null;
}
var synchroniz=false;
function synMember(){
	if(synchroniz ){
		return;
	}
	synchroniz=true;
	var $badge=$('#synBtn .badge').first();
	$badge.hide();
	if($badge.text()==0){
		return;
	}
	
	$('#synBtn i').hide();
	$('#synBtn img').show();
	var param="";
	for(var i=0;i<newContacts.length;i++){
		param+="wxid="+newContacts[i]+"&";
	}
	$.ajax({
		url:"../sms/synContact.json?"+param,
		dataType:"json",
		success:function(data){
			if(data.success){
				synchroniz=false;
				var contacts=data.result;
			 
				for(var i=0;i<contacts.length;i++){
					var contact=contacts[i];
					var html='<li style="border: none;" class="list-group-item" wxid="'+contact.wxid+'" onclick=dialog("'+contact.wxid+'")>';
					html+='<img src="data:image/png;base64,'+contact.headimgurl+'" alt=""><small class="pull-right bg-danger  badge m-r">0</small><strong>'+contact.nickname+'</strong><br>';
					html+='<small class="city">'+contact.province+" "+contact.city+'&nbsp;</small><i class="icon-chevron-right"></i></li>';
					var $li=$(html);
					$contacts[$contacts.length]=$li;
					$li.appendTo('#group'+contact.groupId);
				}
				$('#synBtn').hide();
				$('#synBtn img').hide();
			}else{
				
			}
		}
	});
}

function sortContacts() {
	$("#groups >li").each(function() {
		var $group = $(this);
		var $lis = [];
		$group.find('.contact_group li').each(function() {
			$lis[$lis.length] = $(this);
		});

		for ( var i = 0; i < $lis.length; i++) {
			for ( var j = i + 1; j < $lis.length; j++) {
				if ($lis[i].attr("count") < $lis[j].attr("count")) {
					var temp = $lis[i];
					$lis[i] = $lis[j];
					$lis[j] = temp;
				}
			}
		}
		var $pane = $group.find('.contact_group').first();
		$pane.empty();
		for ( var i = 0; i < $lis.length; i++) {
			$pane.append($lis[i]);
		}
	});

}
function hasOpened(wxid) {
	for ( var i = 0; i < dialogs.length; i++) {
		if (dialogs[i].wxid == wxid) {
			return dialogs[i];
		}
	}
	return false;
}

var msg_timer;
function dialog(wxid) {
	var $item=getContactItem(wxid);
	$item.attr('newMsg',false);
	$item.find(".badge").text(0).hide();
	var $dialog = hasOpened(wxid);
	if (!$dialog) {
		var dialog = $($('#dialog_temp').html());
		var left = document.body.clientWidth / 2 - 300 + (dialogs.length * 50);

		dialog.css("left", left + "px");
		dialog.css("top", "60px");
		dialog.css('z-index', 101);
		dialog.click(function() {
			$('.window').css('z-index', 99);
			dialog.css('z-index', 100);
		});
		var faceWrap = dialog.find('.faceWrap').first();
		dialog.find('.avatar').click(function() {
			var display = faceWrap.css('display');
			if (display == 'none') {
				faceWrap.fadeIn();
			} else {
				faceWrap.fadeOut();
			}
		});
 
		dialog.find('.faceBox a').click(function() {
			var $input = dialog.find('input').first();
			var val = $input.val();
			var title = $(this).attr('title');
			$input.val(val + "[" + title + "]");
			faceWrap.fadeOut();
		});
		// 定义新聊天窗口
		$dialog = {
			wxid : wxid,
			dialog : dialog,
			appendMessage : function(message) {
				// 向窗口添加新消息
				var pull = "left";

				var gzhId = $('#gzhInfo').attr('gzhId');
				if (gzhId == message.fromUserName) {
					pull = "right";
				}
				var date = new Date().setTime(parseInt(message.createTime));
				var html = '<article class="chat-item comment-item media arrow arrow-'+ pull+ '" mid="'+ message.id+ '" id="comment'+ message.id + '"> ';
				html += '<a class="pull-' + pull + ' thumb-small">';
				html += '	<img src="' + message.icon+ '" style="width:30px;height: 30px">';
				html += '</a> ';
				html += '<section class="media-body pull-' + pull + '"> ';
				html += '	<div class="panel text-small m-b-none"> ';
				var msg = message.msg;
				for ( var i = 0; i < facenames.length; i++) {
					var face = "<img src='https://wx.qq.com/zh_CN/htmledition/images/qqface/"+ faceimgs[i] + "'>";
					msg=msg.replace(facenames[i],face);
				}

				for ( var i = 0; i < emojis.length; i++) {
					var face = "<img src='https://wx.qq.com/zh_CN/htmledition/images/qqface/"
							+ faceimgs[i] + "'>";

					 msg=msg.replace(emojis[i],face);
				}
			
				html += '		<div class="panel-body">' + msg
						+ '<img class="pull-'
						+ (pull == 'left' ? 'right' : 'left')
						+ ' loading" src="../img/loading1.gif"  id="loading'
						+ message.id + '"/> </div> ';
				html += '	</div>';
				html += '	<div class="time"> <small class="text-muted"> '
						+ message.createTime + '</small> ';
				html += '	 </div>';
				html += ' </section> ';
				html += '</article>';

				var $commentList = this.dialog.find('.comment-list .items')
						.first();
				$(html).appendTo($commentList);
			}
		};
		dialogs[dialogs.length] = $dialog;
		dialog.find('.icon-remove-sign').click(function() {
			dialog.remove();
			dialogs.splice(dialogs.length - 1);
		});
		dialog.find('button').click(function() {
			var text = dialog.find('input').val();
			if (text.length == 0) {
				return;
			}
			send(wxid, text);
			dialog.find('input').val('');
		});
	}
	var dialog = $dialog.dialog;
	var $li = $('li[wxid="' + wxid + '"]').first();
	var userIcon = $li.find("img").attr('src');
	var $chatinfo = dialog.find('.chatinfo').first();
	$chatinfo.find('img').attr("src", userIcon);
	$chatinfo.find('strong').text($li.find('strong').text());
	$chatinfo.find('small').text($li.find('.city').text());

	$.ajax({
		url : "../sms/getUserMessge.json?wxid=" + wxid,
		dataType : "json",
		success : function(data) {
			if (data.success) {
				var result = data.result;
				for ( var i = result.length - 1; i >= 0; i--) {
					var icon = userIcon;
					if (wxid != result[i].fromUserName) {
						icon = $('#gzh-logo').attr('src');
					}
					var message = result[i];
					message.icon = icon;
					$dialog.appendMessage(message);
				}

				dialog.show().appendTo("body");
				dialog.draggable({
					handle : "header",
					containment : "body"
				});
				var $items = dialog.find('.comment-list .items').first();
				var $commentlist = dialog.find('.comment-list');
				$commentlist.animate({
					scrollTop : $items.height()
				});
			}

		}

	});

}

function send(wxid, msg) {

	var $dialog = hasOpened(wxid);
	var dialog = $dialog.dialog;
	var $last = dialog.find('.comment-item').last();

	var date = new Date();
	var ts = date.getTime();

	var message = {
		id : ts,
		msg : msg,
		icon : $('#gzh-logo').attr('src'),
		fromUserName : $('#gzhInfo').attr('gzhId'),
		createTime : date.pattern("yyyy-MM-dd hh:mm:ss")
	};

	$dialog.appendMessage(message);
	$('#loading' + ts).show();
	var $items = dialog.find('.comment-list .items').first();
	var $msgbody = dialog.find('.comment-list').first();
	$msgbody.animate({
		scrollTop : $items.height()
	}, "slow");

	$.ajax({
		url : "../sms/send.json",
		data : {
			wxid : wxid,
			msg : msg
		},
		type : "post",
		dataType : "json",
		success : function(data) {
			if (data.success) {
				$('#loading' + ts).hide();
				$("#comment" + ts).attr('mid', data.attribute['id']);
			} else {
				$('#loading' + ts).attr('src',
						"../img/msg_state_fail_resend.png");
				$("#comment" + ts).attr('mid', $last.attr('mid'));
				$('#loading' + ts).attr('title', data.message);
			}
		}
	});
}